Popular Searches
Popular Course Categories
Popular Courses

Exception Handling

Selenium with Python

<div class="selenium-notes">

<h1>Exception Handling in Selenium with Python</h1>

<p>Exception Handling is an important concept in Selenium Python automation because automated tests interact with dynamic web applications, browsers, WebDriver sessions, frames, alerts, windows, and changing DOM elements. During execution, unexpected conditions can cause Selenium to raise exceptions.</p>

<p>Exception handling allows automation engineers to detect these failures, handle them appropriately, collect useful diagnostic information, perform cleanup operations, and prevent one unexpected error from making the entire automation framework difficult to debug.</p>

<p>Selenium Python provides WebDriver-specific exceptions such as <strong>NoSuchElementException</strong>, <strong>TimeoutException</strong>, <strong>StaleElementReferenceException</strong>, <strong>ElementClickInterceptedException</strong>, <strong>NoSuchFrameException</strong>, <strong>NoSuchWindowException</strong>, and many others. <strong>WebDriverException</strong> is the base class for WebDriver-related exceptions.</p>

<p><strong>Course Resource:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

 

<h2>1. What is Exception Handling?</h2>

<p>Exception Handling is a programming technique used to detect and manage runtime errors without allowing the application or automation script to terminate unexpectedly.</p>

<p>In Python, exception handling is mainly performed using the following keywords:</p>

<ul>

<li><strong>try</strong> - Contains code that may generate an exception.</li>

<li><strong>except</strong> - Handles a specific exception.</li>

<li><strong>else</strong> - Executes when no exception occurs.</li>

<li><strong>finally</strong> - Executes whether an exception occurs or not.</li>

<li><strong>raise</strong> - Manually raises or propagates an exception.</li>

</ul>

 

<h2>2. Basic Exception Handling Flow</h2>

<pre><code>Start

  |

  v

Execute Code

  |

  v

Exception Occurs?

 /          \

No          Yes

 |           |

 v           v

Continue   Find Matching

           except Block

               |

               v

         Handle Exception

               |

               v

            finally

               |

               v

              End</code></pre>

 

<h2>3. Why Exception Handling is Important in Selenium</h2>

<p>Selenium tests interact with external systems whose state can change during execution. An element may not exist yet, a locator may become invalid, a page may refresh, a frame may not be available, a browser window may close, or a timeout may occur.</p>

<p>Proper exception handling helps automation frameworks:</p>

<ul>

<li>Prevent uncontrolled test termination.</li>

<li>Identify the actual cause of failures.</li>

<li>Generate meaningful error messages.</li>

<li>Capture screenshots when appropriate.</li>

<li>Perform browser cleanup.</li>

<li>Improve debugging.</li>

<li>Support test reporting.</li>

<li>Separate recoverable failures from genuine test failures.</li>

<li>Make automation frameworks more maintainable.</li>

</ul>

 

<h2>4. Basic Python try-except</h2>

<pre><code>try:

    print(10 / 0)

except:

    print("An exception occurred")</code></pre>

<p>Although a bare <code>except:</code> is possible, it is generally better to catch specific exceptions so that the automation framework can respond appropriately.</p>

 

<h2>5. Handling a Specific Exception</h2>

<pre><code>try:

    number = 10 / 0

except ZeroDivisionError:

    print("Cannot divide by zero")</code></pre>

<p>Specific exception handling makes the code easier to understand and prevents unrelated exceptions from being hidden.</p>

 

<hr>

 

<h2>6. Selenium Exception Hierarchy</h2>

<pre><code>Exception

    |

    v

WebDriverException

    |

    +-- NoSuchElementException

    +-- TimeoutException

    +-- StaleElementReferenceException

    +-- ElementNotInteractableException

    +-- ElementClickInterceptedException

    +-- InvalidElementStateException

    +-- NoSuchFrameException

    +-- NoSuchWindowException

    +-- NoAlertPresentException

    +-- UnexpectedAlertPresentException

    +-- InvalidSelectorException

    +-- JavascriptException

    +-- SessionNotCreatedException

    +-- NoSuchDriverException

    +-- NoSuchCookieException

    +-- ScreenshotException</code></pre>

<p>Selenium provides specialized exception classes so automation engineers can identify different types of WebDriver failures and handle them appropriately.</p>

 

<h2>7. Importing Selenium Exceptions</h2>

<pre><code>from selenium.common.exceptions import (

    NoSuchElementException,

    TimeoutException,

    StaleElementReferenceException,

    ElementNotInteractableException,

    ElementClickInterceptedException,

    InvalidElementStateException,

    NoSuchFrameException,

    NoSuchWindowException,

    NoAlertPresentException,

    UnexpectedAlertPresentException,

    InvalidSelectorException,

    JavascriptException,

    WebDriverException

)</code></pre>

 

<h2>8. NoSuchElementException</h2>

<p><strong>NoSuchElementException</strong> occurs when Selenium cannot find the requested element at the time the lookup is performed.</p>

 

<h3>Example</h3>

<pre><code>from selenium.common.exceptions import NoSuchElementException

from selenium.webdriver.common.by import By

 

try:

    username = driver.find_element(By.ID, "username")

    username.send_keys("admin")

except NoSuchElementException:

    print("Username field was not found")</code></pre>

 

<h3>Possible Causes</h3>

<ul>

<li>Incorrect locator.</li>

<li>Element has not appeared yet.</li>

<li>Page is not loaded as expected.</li>

<li>Wrong page or URL.</li>

<li>Element is inside an iframe.</li>

<li>DOM structure has changed.</li>

<li>Previous action did not complete successfully.</li>

</ul>

 

<h3>Better Approach with Explicit Wait</h3>

<pre><code>from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

username = WebDriverWait(driver, 10).until(

    EC.visibility_of_element_located(

        (By.ID, "username")

    )

)</code></pre>

 

<p>Instead of immediately searching for a dynamic element, use an appropriate wait condition when the application requires synchronization.</p>

 

<hr>

 

<h2>9. TimeoutException</h2>

<p><strong>TimeoutException</strong> occurs when an operation or wait does not complete within the required amount of time. It is commonly encountered when an explicit wait condition is not satisfied before the timeout expires.</p>

 

<pre><code>from selenium.common.exceptions import TimeoutException

 

try:

    button = WebDriverWait(driver, 10).until(

        EC.element_to_be_clickable(

            (By.ID, "login")

        )

    )

    button.click()

 

except TimeoutException:

    print("Login button did not become clickable")</code></pre>

 

<h3>Common Causes</h3>

<ul>

<li>Element never appeared.</li>

<li>Incorrect locator.</li>

<li>Application response was slower than expected.</li>

<li>Element remained disabled.</li>

<li>Loading overlay remained visible.</li>

<li>Expected URL did not occur.</li>

<li>Expected text did not appear.</li>

</ul>

 

<hr>

 

<h2>10. StaleElementReferenceException</h2>

<p><strong>StaleElementReferenceException</strong> occurs when Selenium has a reference to an element that is no longer attached to the current DOM. This can happen after page refreshes, DOM replacements, navigation, or JavaScript frameworks rebuilding elements.</p>

 

<h3>Example</h3>

<pre><code>from selenium.common.exceptions import StaleElementReferenceException

 

try:

    button = driver.find_element(By.ID, "submit")

 

    # Application updates the DOM

 

    button.click()

 

except StaleElementReferenceException:

    print("The element became stale")</code></pre>

 

<h3>Common Solution</h3>

<p>Locate the element again after the DOM has changed.</p>

<pre><code>try:

    button = driver.find_element(By.ID, "submit")

    button.click()

 

except StaleElementReferenceException:

    button = driver.find_element(By.ID, "submit")

    button.click()</code></pre>

 

<h3>Better Approach with Wait</h3>

<pre><code>button = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable(

        (By.ID, "submit")

    )

)

 

button.click()</code></pre>

 

<hr>

 

<h2>11. ElementNotInteractableException</h2>

<p><strong>ElementNotInteractableException</strong> can occur when Selenium finds an element but the element cannot currently be interacted with. The element may be hidden, disabled, or otherwise not in a state suitable for the requested interaction.</p>

 

<pre><code>from selenium.common.exceptions import ElementNotInteractableException

 

try:

    driver.find_element(

        By.ID, "username"

    ).send_keys("admin")

 

except ElementNotInteractableException:

    print("Username field is not currently interactable")</code></pre>

 

<h3>Possible Solutions</h3>

<ul>

<li>Wait for visibility.</li>

<li>Wait for clickability where appropriate.</li>

<li>Check whether the element is enabled.</li>

<li>Verify that the correct element was located.</li>

<li>Check whether another UI element is blocking the interaction.</li>

</ul>

 

<hr>

 

<h2>12. ElementClickInterceptedException</h2>

<p><strong>ElementClickInterceptedException</strong> occurs when a click cannot reach the intended element because another element is obscuring or intercepting the click.</p>

 

<pre><code>from selenium.common.exceptions import ElementClickInterceptedException

 

try:

    driver.find_element(By.ID, "submit").click()

 

except ElementClickInterceptedException:

    print("Another element intercepted the click")</code></pre>

 

<h3>Common Causes</h3>

<ul>

<li>Popup overlay.</li>

<li>Cookie banner.</li>

<li>Loading spinner.</li>

<li>Modal dialog.</li>

<li>Animation.</li>

<li>Another element positioned above the button.</li>

</ul>

 

<h3>Better Solution</h3>

<pre><code>wait = WebDriverWait(driver, 10)

 

wait.until(

    EC.invisibility_of_element_located(

        (By.ID, "loader")

    )

)

 

button = wait.until(

    EC.element_to_be_clickable(

        (By.ID, "submit")

    )

)

 

button.click()</code></pre>

 

<hr>

 

<h2>13. InvalidElementStateException</h2>

<p><strong>InvalidElementStateException</strong> can occur when an operation cannot be completed because the element is in an invalid state for that operation.</p>

 

<pre><code>from selenium.common.exceptions import InvalidElementStateException

 

try:

    field = driver.find_element(By.ID, "username")

    field.clear()

 

except InvalidElementStateException:

    print("Element is not in a valid state for this operation")</code></pre>

 

<h2>14. NoSuchFrameException</h2>

<p><strong>NoSuchFrameException</strong> occurs when Selenium attempts to switch to a frame that does not exist or cannot be found in the current context.</p>

 

<pre><code>from selenium.common.exceptions import NoSuchFrameException

 

try:

    driver.switch_to.frame("payment-frame")

 

except NoSuchFrameException:

    print("Payment frame was not found")</code></pre>

 

<h3>Better Approach</h3>

<pre><code>try:

    WebDriverWait(driver, 10).until(

        EC.frame_to_be_available_and_switch_to_it(

            (By.ID, "payment-frame")

        )

    )

 

except TimeoutException:

    print("Payment frame did not become available")</code></pre>

 

<hr>

 

<h2>15. NoSuchWindowException</h2>

<p><strong>NoSuchWindowException</strong> occurs when Selenium attempts to switch to a browser window or tab that does not exist in the current session.</p>

 

<pre><code>from selenium.common.exceptions import NoSuchWindowException

 

try:

    driver.switch_to.window(window_handle)

 

except NoSuchWindowException:

    print("Browser window does not exist")</code></pre>

 

<h3>Checking Window Handles</h3>

<pre><code>print(driver.window_handles)

 

for handle in driver.window_handles:

    print(handle)</code></pre>

 

<hr>

 

<h2>16. NoAlertPresentException</h2>

<p><strong>NoAlertPresentException</strong> occurs when Selenium attempts to interact with an alert when no alert is currently present.</p>

 

<pre><code>from selenium.common.exceptions import NoAlertPresentException

 

try:

    alert = driver.switch_to.alert

    alert.accept()

 

except NoAlertPresentException:

    print("No alert is currently present")</code></pre>

 

<h3>Better Approach with Wait</h3>

<pre><code>alert = WebDriverWait(driver, 10).until(

    EC.alert_is_present()

)

 

alert.accept()</code></pre>

 

<hr>

 

<h2>17. UnexpectedAlertPresentException</h2>

<p><strong>UnexpectedAlertPresentException</strong> can occur when an unexpected modal alert blocks WebDriver from executing a command.</p>

 

<pre><code>from selenium.common.exceptions import UnexpectedAlertPresentException

 

try:

    driver.find_element(By.ID, "submit").click()

 

except UnexpectedAlertPresentException:

    print("An unexpected alert is blocking the browser")</code></pre>

 

<h2>18. InvalidSelectorException</h2>

<p><strong>InvalidSelectorException</strong> occurs when the selector supplied to Selenium is invalid. This commonly happens with syntactically invalid XPath or CSS selectors.</p>

 

<pre><code>from selenium.common.exceptions import InvalidSelectorException

 

try:

    driver.find_element(

        By.XPATH,

        "//*[@id='username'"

    )

 

except InvalidSelectorException:

    print("Invalid XPath selector")</code></pre>

 

<h3>Best Practices</h3>

<ul>

<li>Validate XPath syntax.</li>

<li>Validate CSS selector syntax.</li>

<li>Use the correct <code>By</code> strategy.</li>

<li>Test locators in browser developer tools.</li>

<li>Prefer stable locators.</li>

</ul>

 

<hr>

 

<h2>19. JavascriptException</h2>

<p><strong>JavascriptException</strong> is raised when an error occurs while executing JavaScript supplied by the user.</p>

 

<pre><code>from selenium.common.exceptions import JavascriptException

 

try:

    driver.execute_script(

        "invalid javascript code"

    )

 

except JavascriptException:

    print("JavaScript execution failed")</code></pre>

 

<h2>20. NoSuchCookieException</h2>

<p><strong>NoSuchCookieException</strong> can occur when Selenium cannot find a requested cookie.</p>

 

<pre><code>from selenium.common.exceptions import NoSuchCookieException

 

try:

    cookie = driver.get_cookie("session_id")

 

    if cookie is None:

        print("Cookie was not found")

 

except NoSuchCookieException:

    print("Cookie does not exist")</code></pre>

 

<h2>21. SessionNotCreatedException</h2>

<p><strong>SessionNotCreatedException</strong> can occur when Selenium cannot create a new browser session.</p>

 

<pre><code>from selenium.common.exceptions import SessionNotCreatedException

from selenium import webdriver

 

try:

    driver = webdriver.Chrome()

 

except SessionNotCreatedException:

    print("Unable to create browser session")</code></pre>

 

<h3>Possible Causes</h3>

<ul>

<li>Browser and driver incompatibility.</li>

<li>Invalid browser configuration.</li>

<li>Driver startup failure.</li>

<li>Incorrect browser options.</li>

<li>Environment or installation problems.</li>

</ul>

 

<hr>

 

<h2>22. NoSuchDriverException</h2>

<p><strong>NoSuchDriverException</strong> is raised when the required WebDriver cannot be located or specified correctly.</p>

 

<pre><code>from selenium.common.exceptions import NoSuchDriverException

from selenium import webdriver

 

try:

    driver = webdriver.Chrome()

 

except NoSuchDriverException:

    print("Chrome WebDriver could not be located")</code></pre>

 

<h2>23. WebDriverException</h2>

<p><strong>WebDriverException</strong> is the base class for Selenium WebDriver exceptions. It can be caught when a framework needs to handle a broad category of WebDriver errors.</p>

 

<pre><code>from selenium.common.exceptions import WebDriverException

 

try:

    driver.get("https://example.com")

 

except WebDriverException as e:

    print("WebDriver error occurred:", e)</code></pre>

 

<p>However, catching the broad base exception everywhere can hide the actual cause. Specific exceptions are generally preferable when the framework can respond differently to different failures.</p>

 

<hr>

 

<h2>24. Multiple except Blocks</h2>

<p>Python allows multiple exception handlers for different types of errors.</p>

 

<pre><code>try:

    element = driver.find_element(By.ID, "login")

    element.click()

 

except NoSuchElementException:

    print("Login element was not found")

 

except ElementClickInterceptedException:

    print("Another element blocked the click")

 

except ElementNotInteractableException:

    print("Login element cannot be interacted with")

 

except Exception as e:

    print("Unexpected error:", e)</code></pre>

 

<h2>25. Order of except Blocks</h2>

<p>More specific exceptions should normally be handled before broader exception classes.</p>

 

<pre><code>try:

    element = driver.find_element(By.ID, "login")

 

except NoSuchElementException:

    print("Element not found")

 

except WebDriverException:

    print("General WebDriver error")</code></pre>

 

<p>This structure allows the framework to provide specific handling before falling back to broader WebDriver error handling.</p>

 

<hr>

 

<h2>26. Using else with Selenium</h2>

<p>The <strong>else</strong> block executes when no exception occurs in the try block.</p>

 

<pre><code>try:

    element = driver.find_element(By.ID, "username")

 

except NoSuchElementException:

    print("Username field not found")

 

else:

    element.send_keys("admin")

    print("Username entered successfully")</code></pre>

 

<h2>27. Using finally with Selenium</h2>

<p>The <strong>finally</strong> block executes whether an exception occurs or not. It is particularly useful for browser cleanup.</p>

 

<pre><code>driver = None

 

try:

    driver = webdriver.Chrome()

    driver.get("https://example.com")

 

    element = driver.find_element(By.ID, "username")

    element.send_keys("admin")

 

except WebDriverException as e:

    print("Selenium error:", e)

 

finally:

    if driver:

        driver.quit()</code></pre>

 

<h2>28. Complete try-except-else-finally Example</h2>

<pre><code>from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.common.exceptions import (

    NoSuchElementException,

    WebDriverException

)

 

driver = None

 

try:

    driver = webdriver.Chrome()

    driver.get("https://example.com")

 

    username = driver.find_element(By.ID, "username")

    username.send_keys("admin")

 

except NoSuchElementException:

    print("Username field was not found")

 

except WebDriverException as e:

    print("WebDriver error:", e)

 

else:

    print("Test step completed successfully")

 

finally:

    if driver:

        driver.quit()

        print("Browser closed")</code></pre>

 

<hr>

 

<h2>29. Raising an Exception</h2>

<p>The <strong>raise</strong> keyword can be used when the test framework detects an invalid state and wants to stop or propagate the failure explicitly.</p>

 

<pre><code>if not login_successful:

    raise Exception("Login failed")</code></pre>

 

<h2>30. Raising a Custom Exception</h2>

<pre><code>class LoginFailedException(Exception):

    pass

 

if not login_successful:

    raise LoginFailedException(

        "Login operation failed"

    )</code></pre>

 

<h2>31. Custom Exceptions in Selenium Frameworks</h2>

<p>Custom exceptions can make a large automation framework easier to understand.</p>

 

<pre><code>class PageLoadException(Exception):

    pass

 

class LoginException(Exception):

    pass

 

class ElementActionException(Exception):

    pass</code></pre>

 

<p>Example:</p>

<pre><code>try:

    WebDriverWait(driver, 15).until(

        EC.url_contains("/dashboard")

    )

 

except TimeoutException:

    raise LoginException(

        "Dashboard was not reached after login"

    )</code></pre>

 

<hr>

 

<h2>32. Exception Handling with Explicit Waits</h2>

<p>Wait-related exceptions are common in Selenium automation. A framework can catch <strong>TimeoutException</strong> and collect diagnostic information.</p>

 

<pre><code>try:

    login_button = WebDriverWait(

        driver, 10

    ).until(

        EC.element_to_be_clickable(

            (By.ID, "login")

        )

    )

 

    login_button.click()

 

except TimeoutException:

    print("Login button was not ready")

    driver.save_screenshot("login_timeout.png")</code></pre>

 

<h2>33. Exception Handling with Screenshot</h2>

<p>Taking a screenshot at the point of failure can help diagnose UI automation problems.</p>

 

<pre><code>try:

    driver.find_element(

        By.ID, "submit"

    ).click()

 

except WebDriverException as e:

    driver.save_screenshot(

        "selenium_error.png"

    )

    print("Error:", e)</code></pre>

 

<h2>34. Screenshot Utility</h2>

<pre><code>def capture_screenshot(driver, filename):

    try:

        driver.save_screenshot(filename)

        print("Screenshot saved:", filename)

    except Exception as e:

        print("Screenshot failed:", e)</code></pre>

 

<hr>

 

<h2>35. Logging Exceptions</h2>

<p>Logging is preferable to relying only on print statements in larger automation frameworks.</p>

 

<pre><code>import logging

 

logging.basicConfig(

    level=logging.INFO

)

 

try:

    driver.find_element(

        By.ID, "username"

    ).send_keys("admin")

 

except NoSuchElementException as e:

    logging.error(

        "Username element not found: %s",

        e

    )</code></pre>

 

<h2>36. Logging Different Exceptions</h2>

<pre><code>try:

    button = WebDriverWait(driver, 10).until(

        EC.element_to_be_clickable(

            (By.ID, "submit")

        )

    )

    button.click()

 

except TimeoutException:

    logging.error(

        "Submit button was not clickable"

    )

 

except ElementClickInterceptedException:

    logging.error(

        "Submit click was intercepted"

    )

 

except WebDriverException as e:

    logging.error(

        "WebDriver failure: %s",

        e

    )</code></pre>

 

<hr>

 

<h2>37. Exception Handling in Page Object Model</h2>

<p>Exception handling can be placed inside Page Object methods when the page object can provide meaningful recovery or diagnostic information.</p>

 

<pre><code>class LoginPage:

    USERNAME = (By.ID, "username")

    PASSWORD = (By.ID, "password")

    LOGIN = (By.ID, "login")

 

    def __init__(self, driver):

        self.driver = driver

        self.wait = WebDriverWait(driver, 10)

 

    def login(self, username, password):

        try:

            self.wait.until(

                EC.visibility_of_element_located(

                    self.USERNAME

                )

            ).send_keys(username)

 

            self.wait.until(

                EC.visibility_of_element_located(

                    self.PASSWORD

                )

            ).send_keys(password)

 

            self.wait.until(

                EC.element_to_be_clickable(

                    self.LOGIN

                )

            ).click()

 

        except TimeoutException as e:

            self.driver.save_screenshot(

                "login_timeout.png"

            )

            raise e</code></pre>

 

<h2>38. Exception Handling in Test Cases</h2>

<pre><code>def test_login(driver):

    try:

        login_page = LoginPage(driver)

 

        login_page.login(

            "admin",

            "admin123"

        )

 

        assert "/dashboard" in driver.current_url

 

    except AssertionError:

        driver.save_screenshot(

            "login_assertion_failure.png"

        )

        raise

 

    except WebDriverException:

        driver.save_screenshot(

            "webdriver_failure.png"

        )

        raise</code></pre>

 

<hr>

 

<h2>39. Exception Handling vs Waits</h2>

<p>Exception handling and waits solve different problems.</p>

 

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Concept</th><th>Purpose</th></tr>

<tr><td>Wait</td><td>Synchronizes automation with application state.</td></tr>

<tr><td>try-except</td><td>Handles an exception after an operation fails.</td></tr>

<tr><td>Expected Condition</td><td>Defines the state Selenium should wait for.</td></tr>

<tr><td>finally</td><td>Performs cleanup regardless of success or failure.</td></tr>

<tr><td>Logging</td><td>Records diagnostic information.</td></tr>

<tr><td>Screenshot</td><td>Captures visual evidence of failure.</td></tr>

<tr><td>raise</td><td>Explicitly propagates or creates an exception.</td></tr>

</table>

 

<h2>40. Do Not Use Exception Handling as a Replacement for Waits</h2>

<p>A common mistake is repeatedly catching <strong>NoSuchElementException</strong> instead of synchronizing with the application.</p>

 

<pre><code>try:

    button = driver.find_element(By.ID, "submit")

    button.click()

 

except NoSuchElementException:

    time.sleep(5)

    button = driver.find_element(By.ID, "submit")

    button.click()</code></pre>

 

<p>A condition-based wait is usually a better approach:</p>

 

<pre><code>button = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable(

        (By.ID, "submit")

    )

)

 

button.click()</code></pre>

 

<hr>

 

<h2>41. Retry Handling</h2>

<p>Some failures may be temporary, particularly in highly dynamic applications. A retry mechanism can be useful when applied carefully.</p>

 

<pre><code>from selenium.common.exceptions import StaleElementReferenceException

 

for attempt in range(3):

    try:

        button = driver.find_element(

            By.ID, "submit"

        )

        button.click()

        break

 

    except StaleElementReferenceException:

        print(

            f"Attempt {attempt + 1} failed due to stale element"

        )</code></pre>

 

<p>Retries should not be used to hide genuine application defects or incorrect locators.</p>

 

<h2>42. Retry with a Function</h2>

<pre><code>def click_with_retry(driver, locator, attempts=3):

    for attempt in range(attempts):

        try:

            element = driver.find_element(*locator)

            element.click()

            return True

 

        except StaleElementReferenceException:

            if attempt == attempts - 1:

                raise

 

    return False</code></pre>

 

<h2>43. Exception Handling for Dynamic Elements</h2>

<pre><code>def safe_click(driver, locator):

    try:

        element = WebDriverWait(

            driver, 10

        ).until(

            EC.element_to_be_clickable(locator)

        )

 

        element.click()

        return True

 

    except TimeoutException:

        print(

            f"Element was not clickable: {locator}"

        )

        return False

 

    except ElementClickInterceptedException:

        print(

            f"Click intercepted: {locator}"

        )

        return False</code></pre>

 

<hr>

 

<h2>44. Safe Element Finding Utility</h2>

<pre><code>def find_element_safe(driver, locator):

    try:

        return driver.find_element(*locator)

 

    except NoSuchElementException:

        print(

            f"Element not found: {locator}"

        )

        return None</code></pre>

 

<h2>45. Safe Text Retrieval</h2>

<pre><code>def get_text_safe(driver, locator):

    try:

        element = WebDriverWait(

            driver, 10

        ).until(

            EC.visibility_of_element_located(locator)

        )

        return element.text

 

    except TimeoutException:

        return None

 

    except StaleElementReferenceException:

        return None</code></pre>

 

<h2>46. Safe Page Navigation</h2>

<pre><code>def open_page(driver, url):

    try:

        driver.get(url)

        return True

 

    except WebDriverException as e:

        print(

            f"Unable to open page: {e}"

        )

        return False</code></pre>

 

<hr>

 

<h2>47. Exception Handling with Frames</h2>

<pre><code>try:

    WebDriverWait(driver, 10).until(

        EC.frame_to_be_available_and_switch_to_it(

            (By.ID, "payment-frame")

        )

    )

 

    card = WebDriverWait(driver, 10).until(

        EC.visibility_of_element_located(

            (By.ID, "card-number")

        )

    )

 

    card.send_keys("4111111111111111")

 

except TimeoutException:

    print(

        "Payment frame or card field was unavailable"

    )

 

except NoSuchFrameException:

    print("Payment frame was not found")

 

finally:

    driver.switch_to.default_content()</code></pre>

 

<h2>48. Exception Handling with Windows</h2>

<pre><code>try:

    original_window = driver.current_window_handle

 

    driver.find_element(

        By.ID, "open-window"

    ).click()

 

    WebDriverWait(driver, 10).until(

        EC.number_of_windows_to_be(2)

    )

 

    for handle in driver.window_handles:

        if handle != original_window:

            driver.switch_to.window(handle)

            break

 

except TimeoutException:

    print("New window did not open")

 

except NoSuchWindowException:

    print("Window could not be accessed")

 

finally:

    if original_window in driver.window_handles:

        driver.switch_to.window(original_window)</code></pre>

 

<hr>

 

<h2>49. Exception Handling with Alerts</h2>

<pre><code>try:

    driver.find_element(

        By.ID, "delete"

    ).click()

 

    alert = WebDriverWait(

        driver, 10

    ).until(

        EC.alert_is_present()

    )

 

    print(alert.text)

    alert.accept()

 

except TimeoutException:

    print("Alert did not appear")

 

except NoAlertPresentException:

    print("No alert was present")</code></pre>

 

<h2>50. Exception Handling with JavaScript</h2>

<pre><code>from selenium.common.exceptions import JavascriptException

 

try:

    result = driver.execute_script(

        "return document.title;"

    )

    print(result)

 

except JavascriptException as e:

    print(

        "JavaScript execution failed:",

        e

    )</code></pre>

 

<hr>

 

<h2>51. Complete Selenium Exception Handling Framework Example</h2>

<pre><code>import logging

 

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

from selenium.common.exceptions import (

    TimeoutException,

    NoSuchElementException,

    StaleElementReferenceException,

    ElementClickInterceptedException,

    WebDriverException

)

 

logging.basicConfig(

    level=logging.INFO,

    format="%(asctime)s - %(levelname)s - %(message)s"

)

 

driver = None

 

try:

    driver = webdriver.Chrome()

    driver.get("https://example.com/login")

 

    wait = WebDriverWait(driver, 10)

 

    username = wait.until(

        EC.visibility_of_element_located(

            (By.ID, "username")

        )

    )

 

    password = wait.until(

        EC.visibility_of_element_located(

            (By.ID, "password")

        )

    )

 

    login_button = wait.until(

        EC.element_to_be_clickable(

            (By.ID, "login")

        )

    )

 

    username.send_keys("admin")

    password.send_keys("admin123")

    login_button.click()

 

    wait.until(

        EC.url_contains("/dashboard")

    )

 

    logging.info("Login successful")

 

except TimeoutException as e:

    logging.error(

        "Timeout occurred: %s",

        e

    )

 

    if driver:

        driver.save_screenshot(

            "timeout_failure.png"

        )

 

except NoSuchElementException as e:

    logging.error(

        "Element not found: %s",

        e

    )

 

    if driver:

        driver.save_screenshot(

            "element_failure.png"

        )

 

except StaleElementReferenceException as e:

    logging.error(

        "Stale element: %s",

        e

    )

 

except ElementClickInterceptedException as e:

    logging.error(

        "Click intercepted: %s",

        e

    )

 

except WebDriverException as e:

    logging.error(

        "WebDriver exception: %s",

        e

    )

 

finally:

    if driver:

        driver.quit()

        logging.info("Browser closed")</code></pre>

 

<hr>

 

<h2>52. Exception Handling Flow in a Professional Framework</h2>

<pre><code>Test Starts

     |

     v

Open Browser

     |

     v

Execute Test Step

     |

     v

Exception?

  /       \

No         Yes

 |           |

 v           v

Continue   Identify Type

              |

        +-----+-----+------+

        |     |     |      |

        v     v     v      v

      Wait  Locator Click  Other

        |     |     |      |

        +-----+-----+------+

              |

              v

        Log Failure

              |

              v

       Capture Evidence

              |

              v

        Cleanup/Teardown

              |

              v

          Test Report</code></pre>

 

<h2>53. Common Exception Handling Mistakes</h2>

 

<h3>Mistake 1: Catching Every Exception</h3>

<pre><code>try:

    driver.find_element(By.ID, "login").click()

except:

    pass</code></pre>

<p>This hides the actual problem and makes debugging difficult.</p>

 

<h3>Mistake 2: Empty Exception Handler</h3>

<pre><code>except Exception:

    pass</code></pre>

<p>An exception should normally be logged, handled, re-raised, or otherwise accounted for.</p>

 

<h3>Mistake 3: Using sleep Instead of Proper Synchronization</h3>

<pre><code>except NoSuchElementException:

    time.sleep(10)</code></pre>

<p>Use an appropriate Selenium wait when the application condition is known.</p>

 

<h3>Mistake 4: Catching WebDriverException Too Early</h3>

<pre><code>try:

    ...

except WebDriverException:

    print("Error")</code></pre>

<p>If this appears before more specific handlers, specific failures may not receive specialized handling.</p>

 

<h3>Mistake 5: Not Re-Raising Test Failures</h3>

<pre><code>except AssertionError:

    print("Test failed")</code></pre>

<p>In many test frameworks, silently consuming an assertion failure can incorrectly prevent the test from being reported as failed. If the failure should remain a test failure, re-raise it after collecting diagnostics.</p>

 

<h3>Mistake 6: Closing the Browser Too Early</h3>

<p>Do not close the browser before collecting the evidence required for debugging.</p>

 

<hr>

 

<h2>54. Best Practices for Exception Handling in Selenium</h2>

<ul>

<li>Catch specific Selenium exceptions whenever possible.</li>

<li>Use explicit waits for dynamic application states.</li>

<li>Do not use exceptions as the primary synchronization mechanism.</li>

<li>Log meaningful error messages.</li>

<li>Capture screenshots for important UI failures.</li>

<li>Keep browser cleanup in a finally block or framework teardown mechanism.</li>

<li>Re-raise failures when the test should remain failed.</li>

<li>Use reusable utility functions for repeated error handling.</li>

<li>Keep exception handling close to the operation when recovery is possible.</li>

<li>Do not silently ignore exceptions.</li>

<li>Use custom exceptions when they improve framework readability.</li>

<li>Keep retry logic limited and purposeful.</li>

<li>Record the locator, URL, test step, and exception type in framework logs.</li>

<li>Use Page Object Model to organize page-specific interaction logic.</li>

<li>Use test reports to expose failures clearly.</li>

</ul>

 

<h2>55. Exception Handling Strategy Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Exception</th><th>Typical Situation</th><th>Possible Response</th></tr>

<tr><td>NoSuchElementException</td><td>Element cannot be found</td><td>Check locator, page state, frame, and wait strategy</td></tr>

<tr><td>TimeoutException</td><td>Condition not satisfied in time</td><td>Check condition, locator, timeout, and application state</td></tr>

<tr><td>StaleElementReferenceException</td><td>Element reference is no longer valid</td><td>Locate the element again</td></tr>

<tr><td>ElementNotInteractableException</td><td>Element cannot currently be interacted with</td><td>Check visibility, enabled state, and UI state</td></tr>

<tr><td>ElementClickInterceptedException</td><td>Another element blocks the click</td><td>Wait for overlay or blocking element to disappear</td></tr>

<tr><td>InvalidElementStateException</td><td>Element is in an invalid state</td><td>Verify element state before operation</td></tr>

<tr><td>NoSuchFrameException</td><td>Frame cannot be found</td><td>Verify frame locator and context</td></tr>

<tr><td>NoSuchWindowException</td><td>Window/tab does not exist</td><td>Verify window handles</td></tr>

<tr><td>NoAlertPresentException</td><td>No alert is available</td><td>Wait for alert or verify application flow</td></tr>

<tr><td>UnexpectedAlertPresentException</td><td>Unexpected alert blocks command</td><td>Handle alert appropriately</td></tr>

<tr><td>InvalidSelectorException</td><td>Invalid XPath/CSS selector</td><td>Correct and validate locator</td></tr>

<tr><td>JavascriptException</td><td>JavaScript execution fails</td><td>Validate JavaScript</td></tr>

<tr><td>SessionNotCreatedException</td><td>Browser session cannot start</td><td>Check browser, driver, and configuration</td></tr>

<tr><td>NoSuchDriverException</td><td>Driver cannot be located</td><td>Check WebDriver setup</td></tr>

<tr><td>WebDriverException</td><td>General WebDriver failure</td><td>Log and investigate underlying cause</td></tr>

</table>

 

<h2>56. Real-World Login Exception Handling</h2>

<pre><code>def login(driver, username, password):

    wait = WebDriverWait(driver, 10)

 

    try:

        user_field = wait.until(

            EC.visibility_of_element_located(

                (By.ID, "username")

            )

        )

 

        password_field = wait.until(

            EC.visibility_of_element_located(

                (By.ID, "password")

            )

        )

 

        login_button = wait.until(

            EC.element_to_be_clickable(

                (By.ID, "login")

            )

        )

 

        user_field.send_keys(username)

        password_field.send_keys(password)

        login_button.click()

 

        wait.until(

            EC.url_contains("/dashboard")

        )

 

        return True

 

    except TimeoutException:

        driver.save_screenshot(

            "login_timeout.png"

        )

        return False

 

    except WebDriverException as e:

        driver.save_screenshot(

            "login_webdriver_error.png"

        )

        print("WebDriver error:", e)

        return False</code></pre>

 

<h2>57. Real-World E-Commerce Exception Handling</h2>

<pre><code>def add_product_to_cart(driver):

    wait = WebDriverWait(driver, 15)

 

    try:

        product = wait.until(

            EC.element_to_be_clickable(

                (By.CSS_SELECTOR, ".product")

            )

        )

 

        product.click()

 

        add_button = wait.until(

            EC.element_to_be_clickable(

                (By.ID, "add-to-cart")

            )

        )

 

        add_button.click()

 

        wait.until(

            EC.text_to_be_present_in_element(

                (By.ID, "cart-message"),

                "Added"

            )

        )

 

        return True

 

    except TimeoutException:

        driver.save_screenshot(

            "cart_timeout.png"

        )

        return False

 

    except ElementClickInterceptedException:

        driver.save_screenshot(

            "cart_click_intercepted.png"

        )

        return False

 

    except StaleElementReferenceException:

        print(

            "Product element became stale"

        )

        return False</code></pre>

 

<hr>

 

<h2>58. Practical Project: Selenium Exception Handling Framework</h2>

<p>Create a Selenium Python automation framework with centralized exception handling.</p>

 

<h3>Requirements</h3>

<ol>

<li>Create a BaseTest class.</li>

<li>Create browser setup and teardown methods.</li>

<li>Create reusable wait utilities.</li>

<li>Create screenshot utilities.</li>

<li>Create logging utilities.</li>

<li>Create Page Object classes.</li>

<li>Handle common Selenium exceptions.</li>

<li>Capture screenshots on failures.</li>

<li>Record exception details in logs.</li>

<li>Re-raise failures when required.</li>

<li>Generate a test report.</li>

</ol>

 

<h3>Suggested Project Structure</h3>

<pre><code>selenium_project/

|

+-- tests/

|   +-- test_login.py

|   +-- test_cart.py

|

+-- pages/

|   +-- login_page.py

|   +-- product_page.py

|   +-- cart_page.py

|

+-- utilities/

|   +-- wait_helper.py

|   +-- screenshot_helper.py

|   +-- logger.py

|

+-- exceptions/

|   +-- custom_exceptions.py

|

+-- screenshots/

|

+-- logs/

|

+-- reports/

|

+-- conftest.py</code></pre>

 

<hr>

 

<h2>59. Interview Questions on Exception Handling</h2>

 

<h3>Q1. What is exception handling?</h3>

<p>Exception handling is a mechanism for detecting and managing runtime errors without allowing the program to terminate unexpectedly.</p>

 

<h3>Q2. What is NoSuchElementException?</h3>

<p>It occurs when Selenium cannot find the requested element at the time the lookup is performed.</p>

 

<h3>Q3. What is TimeoutException?</h3>

<p>It occurs when a Selenium wait condition is not satisfied within the configured timeout.</p>

 

<h3>Q4. What is StaleElementReferenceException?</h3>

<p>It occurs when a previously located element reference is no longer attached to the current DOM.</p>

 

<h3>Q5. How do you handle stale elements?</h3>

<p>Common approaches include waiting for the appropriate state and locating the element again after the DOM changes.</p>

 

<h3>Q6. What is ElementClickInterceptedException?</h3>

<p>It occurs when another element prevents Selenium from clicking the intended element.</p>

 

<h3>Q7. What is the difference between try and except?</h3>

<p>The try block contains potentially failing code, while the except block handles a matching exception.</p>

 

<h3>Q8. What is finally?</h3>

<p>The finally block executes whether an exception occurs or not and is useful for cleanup.</p>

 

<h3>Q9. Why should specific exceptions be preferred?</h3>

<p>Specific exceptions allow the framework to identify the actual failure type and apply an appropriate response.</p>

 

<h3>Q10. Can we use multiple except blocks?</h3>

<p>Yes. Multiple except blocks can handle different exception types separately.</p>

 

<h3>Q11. What is raise?</h3>

<p>The raise keyword manually creates or propagates an exception.</p>

 

<h3>Q12. Can exception handling replace explicit waits?</h3>

<p>No. Exception handling manages failures, while waits synchronize the automation with application state. They solve different problems.</p>

 

<h3>Q13. What is WebDriverException?</h3>

<p>WebDriverException is the base exception class for Selenium WebDriver-related exceptions.</p>

 

<h3>Q14. How can screenshots help with exceptions?</h3>

<p>A screenshot provides visual evidence of the browser state at the time of failure, which can help diagnose UI automation problems.</p>

 

<h3>Q15. Why should exceptions not be silently ignored?</h3>

<p>Silently ignoring exceptions can hide real application or automation defects and may produce misleading test results.</p>

 

<hr>

 

<h2>60. Quick Revision</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Python Concept</th><th>Purpose</th></tr>

<tr><td>try</td><td>Contains potentially failing code</td></tr>

<tr><td>except</td><td>Handles an exception</td></tr>

<tr><td>else</td><td>Runs when no exception occurs</td></tr>

<tr><td>finally</td><td>Runs regardless of exception</td></tr>

<tr><td>raise</td><td>Raises or propagates an exception</td></tr>

<tr><td>Exception</td><td>General Python exception base</td></tr>

<tr><td>WebDriverException</td><td>Selenium WebDriver exception base</td></tr>

</table>

 

<h2>61. Selenium Exception Quick Revision</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Exception</th><th>Remember It As</th></tr>

<tr><td>NoSuchElementException</td><td>Element not found</td></tr>

<tr><td>TimeoutException</td><td>Condition timed out</td></tr>

<tr><td>StaleElementReferenceException</td><td>Element reference became invalid</td></tr>

<tr><td>ElementNotInteractableException</td><td>Element cannot be interacted with</td></tr>

<tr><td>ElementClickInterceptedException</td><td>Another element blocked click</td></tr>

<tr><td>InvalidElementStateException</td><td>Element is in an invalid state</td></tr>

<tr><td>NoSuchFrameException</td><td>Frame not found</td></tr>

<tr><td>NoSuchWindowException</td><td>Window/tab not found</td></tr>

<tr><td>NoAlertPresentException</td><td>No alert available</td></tr>

<tr><td>UnexpectedAlertPresentException</td><td>Unexpected alert appeared</td></tr>

<tr><td>InvalidSelectorException</td><td>Invalid locator expression</td></tr>

<tr><td>JavascriptException</td><td>JavaScript execution failed</td></tr>

<tr><td>SessionNotCreatedException</td><td>Browser session could not start</td></tr>

<tr><td>NoSuchDriverException</td><td>Driver could not be located</td></tr>

<tr><td>WebDriverException</td><td>General WebDriver error</td></tr>

</table>

 

<h2>62. Recommended Exception Handling Flow</h2>

<pre><code>Perform Selenium Action

        |

        v

Was Action Successful?

      /       \

    Yes        No

     |          |

     v          v

 Continue   Identify Exception

                |

                v

        Specific Exception?

           /          \

         Yes           No

          |             |

          v             v

 Handle Specifically  Log General Error

          |             |

          +------ + -----+

                 |

                 v

        Capture Screenshot

                 |

                 v

        Collect Diagnostic Data

                 |

                 v

          Retry / Recover / Fail

                 |

                 v

               Cleanup</code></pre>

 

<h2>63. Final Summary</h2>

<p>Exception Handling is an essential part of professional Selenium Python automation. Selenium interacts with browsers and dynamic web applications, so failures such as missing elements, timeouts, stale references, intercepted clicks, unavailable frames, missing windows, unexpected alerts, and invalid selectors can occur during test execution.</p>

<p>Python's <strong>try</strong>, <strong>except</strong>, <strong>else</strong>, <strong>finally</strong>, and <strong>raise</strong> mechanisms provide the foundation for handling these situations. Selenium adds specialized WebDriver exceptions that allow automation engineers to identify different failure conditions.</p>

<p>A reliable automation framework should combine <strong>proper waits</strong>, <strong>specific exception handling</strong>, <strong>logging</strong>, <strong>screenshots</strong>, <strong>cleanup</strong>, and appropriate <strong>failure propagation</strong>. Exception handling should make failures easier to diagnose rather than hide them.</p>

 

<h2>64. Course Resources</h2>

<p><strong>Selenium Training:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a></p>

<p><strong>Register for Course Demo:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Selenium Course Demo</a></p>

</div>

Previous Next
whatsapp